package org.eclipse.moquette.spi.impl.subscriptions;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.eclipse.moquette.spi.ISessionsStore;
import org.eclipse.moquette.spi.persistence.RedisStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 简单的订阅存储 不支持目录形式
 */
public class SimpleSubscriptionsStore extends SubscriptionsStore {


    private RedisStore m_sessionsStore;
    private static final Logger LOG = LoggerFactory.getLogger(SubscriptionsStore.class);

    public void init(ISessionsStore sessionsStore) {
        LOG.debug("init invoked");
        m_sessionsStore = (RedisStore) sessionsStore;
    }

    protected void addDirect(Subscription newSubscription) {
    }


    public void add(Subscription newSubscription) {
        addDirect(newSubscription);

    }


    public void removeSubscription(String topic, String clientID) {

        m_sessionsStore.removeSubscription(topic, clientID);
    }


    public void clearAllSubscriptions() {
    }

    public void removeForClient(String clientID) {
        m_sessionsStore.wipeSubscriptions(clientID);
    }

    public void deactivate(String clientID) {
        m_sessionsStore.updateSubscriptions(clientID, sub -> {
            sub.setActive(false);
            return sub;
        });
    }

    public void activate(String clientID) {
        LOG.debug("Activating subscriptions for clientID <{}>", clientID);
        m_sessionsStore.updateSubscriptions(clientID, sub -> {
            sub.setActive(true);
            return sub;
        });
    }

    public List<Subscription> matches(String topic) {
        return m_sessionsStore.getTopicSubscriptions(topic);
    }

    public boolean contains(Subscription sub) {
        return !matches(sub.topicFilter).isEmpty();
    }

    public int size() {
        return 0;
    }


    public static boolean matchTopics(String msgTopic, String subscriptionTopic) {

        return !Strings.isNullOrEmpty(msgTopic) && !Strings.isNullOrEmpty(subscriptionTopic)
                && !msgTopic.equalsIgnoreCase(subscriptionTopic);

    }
}
